package com.ekuaitu.kuaitustaff.activity;

import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ekuaitu.kuaitustaff.BuildConfig;
import com.ekuaitu.kuaitustaff.R;
import com.ekuaitu.kuaitustaff.api.ApiService;
import com.ekuaitu.kuaitustaff.api.ApiStore;
import com.ekuaitu.kuaitustaff.api.JsApi;
import com.ekuaitu.kuaitustaff.api.UrlConstant;
import com.ekuaitu.kuaitustaff.application.MyApplication;
import com.ekuaitu.kuaitustaff.base.BaseActivity;
import com.ekuaitu.kuaitustaff.bean.UploadImageBaidu;
import com.ekuaitu.kuaitustaff.utils.AppManager;
import com.ekuaitu.kuaitustaff.utils.Constants;
import com.ekuaitu.kuaitustaff.utils.IntentKey;
import com.ekuaitu.kuaitustaff.utils.Logger;
import com.ekuaitu.kuaitustaff.utils.NetUtils;
import com.ekuaitu.kuaitustaff.utils.SDCardUtils;
import com.ekuaitu.kuaitustaff.utils.UploadPicUtil;
import com.ekuaitu.kuaitustaff.widget.WebViewProgressBar;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
import wendu.dsbridge.CompletionHandler;
import wendu.dsbridge.DWebView;
import wendu.dsbridge.OnReturnValue;


public class WebViewActivity extends BaseActivity {
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.dWebView)
    DWebView dWebView;
    @BindView(R.id.linear_nonet)
    LinearLayout linear_nonet;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.title_name)
    TextView titleName;

    private String url;
    private Context mContext = this;
    private WebViewProgressBar webViewProgressBar;
    private JsApi jsApi;

    @Override
    public int getLayoutId() {
        return R.layout.activity_web;
    }

    public void setTitle(String name) {
        titleName.setText(name);
    }

    @Override
    public void initView() {
        Intent intent = getIntent();
        url = intent.getStringExtra(IntentKey.INTENT_WEBVIEW_URL);
        Logger.i("webview_url", url);
        syncCookie();
        webViewProgressBar = new WebViewProgressBar(progressBar);
        dWebView.setWebChromeClient(mWebChromeClient);
        dWebView.setWebViewClient(mWebViewClient);
        dWebView.getSettings().setSupportMultipleWindows(false);
        dWebView.getSettings().setAppCacheEnabled(false);
        dWebView.getSettings().setTextZoom(100);
        jsApi = new JsApi(mContext);
        dWebView.addJavascriptObject(jsApi, null);
        if (BuildConfig.DEBUG) {
            dWebView.setWebContentsDebuggingEnabled(true);
        }
        if (!NetUtils.isNetworkAvailable(mContext)) {
            dWebView.setVisibility(View.GONE);
            linear_nonet.setVisibility(View.VISIBLE);
        } else {
            dWebView.setVisibility(View.VISIBLE);
            linear_nonet.setVisibility(View.GONE);
            dWebView.loadUrl(url);
        }

    }

    @Override
    protected void initData() {

    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (webViewProgressBar != null) {
                webViewProgressBar.onProgressStart();
            }
        }

    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (webViewProgressBar != null) {
                webViewProgressBar.onProgressChange(newProgress);
            }
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("imageUrl", MyApplication.imageUrl);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        jsApi.outputImage = new File(mContext.getExternalCacheDir(), "outjs_image.jpg");
        jsApi.dsBridgeHandler = new CompletionHandler<Object>() {
            @Override
            public void complete(Object o) {
            }
            @Override
            public void complete() {
            }
            @Override
            public void setProgressData(Object o) {
            }
        };
        MyApplication.imageUrl = savedInstanceState.getString("imageUrl");
        syncCookie();//imageUrl在cookie丢失，现场保护取到再设置到cookie

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && (requestCode == Constants.REQUEST_CAMERA || requestCode == Constants.REQUEST_ALBUM)) {
            try {
                if (requestCode == Constants.REQUEST_ALBUM && data != null) {
                    //判断手机系统版本号
                    String path = "";
                    if (Build.VERSION.SDK_INT >= 19) {
                        //4.4及以上系统使用这个方法处理图片
                        path = handlerImageOnKitKat(data);
                    } else {
                        //4.4以下系统使用这个方法处理图片
                        path = handlerImageBeforeKitKat(data);
                    }
                    jsApi.outputImage = new File(path);
                }
                Luban.with(mContext)
                        .load(jsApi.outputImage)  //传入要压缩的图片
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                showLoadingDialog();
                            }

                            @Override
                            public void onSuccess(File file) {
                                try {
                                    File newFile = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + SDCardUtils.createImageFileName(((MyApplication) getApplication()).getUserId()) + ".jpg");
                                    file.renameTo(newFile);
                                    uploadImage(newFile, jsApi.dsBridgeHandler);
                                    // 其次把文件插入到系统图库
                                    MediaStore.Images.Media.insertImage(mContext.getContentResolver(),
                                            newFile.getAbsolutePath(), newFile.getName(), null);
                                    // 最后通知图库更新
                                    mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                            Uri.fromFile(new File(newFile.getPath()))));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onError(Throwable e) {
                                dismissLoadingDialog();
                                try {
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("error", e.getMessage() + "");
                                    jsApi.dsBridgeHandler.setProgressData(jsonObject);
                                } catch (Exception ee) {
                                    e.printStackTrace();
                                }
                            }
                        }).launch();    //启动压缩
            } catch (Exception e) {
                dismissLoadingDialog();
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("error", e.getMessage() + "");
                    jsApi.dsBridgeHandler.setProgressData(jsonObject);
                } catch (Exception ee) {
                    ee.printStackTrace();
                }
            }
        }
    }

    private String handlerImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            //如果是document类型的Uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是content类型的URI，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是file类型的Uri,直接获取图片路径即可
            imagePath = uri.getPath();
        }
        return imagePath;
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private String handlerImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        return imagePath;
    }

    @Override
    public void onBackPressed() {
        dWebView.evaluateJavascript("window.dsBridge", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
                Logger.d("jsbridge", s + "NAVI222");
                if (!s.equals("null")) {
                    dWebView.hasJavascriptMethod("DDWEBVIEW_NAV_BACK", new OnReturnValue<Boolean>() {
                        @Override
                        public void onValue(Boolean retValue) {
                            Logger.d("jsbridge", retValue + "NAVI");
                            if (retValue) {
                                dWebView.callHandler("DDWEBVIEW_NAV_BACK", new Object[]{}, new OnReturnValue<String>() {
                                    @Override
                                    public void onValue(String retValue) {
                                        Logger.d("jsbridge", "NAVIRESULT" + retValue);
                                        if ("1".equals(retValue)) {

                                        } else {
                                            AppManager.getAppManager().finishActivity();
                                        }
                                    }
                                });
                            } else {
                                if (!dWebView.canGoBack()) {
                                    AppManager.getAppManager().finishActivity();
                                } else {
                                    dWebView.goBack();
                                }
                            }
                        }
                    });
                } else {
                    if (!dWebView.canGoBack()) {
                        AppManager.getAppManager().finishActivity();
                    } else {
                        dWebView.goBack();
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (webViewProgressBar != null) {
            webViewProgressBar.destroy();
            webViewProgressBar = null;
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }


    @OnClick({R.id.title_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                onBackPressed();
                break;
        }
    }

    public boolean syncCookie() {
        CookieManager cookieManager = CookieManager.getInstance();
        Map<String, String> requestMap = ((MyApplication) getApplication()).getCookieMap();
        for (String mapKey : requestMap.keySet()) {
            cookieManager.setCookie(url, mapKey + "=" + requestMap.get(mapKey));
        }
        String newCookie = cookieManager.getCookie(url);
        Logger.i("webview_url", newCookie);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mContext);
            cookieSyncManager.sync();
        }
        return null != newCookie && !TextUtils.isEmpty(newCookie);
    }

    //获得要上传图片的参数，并上传图片
    public void uploadImage(final File picFile, CompletionHandler<Object> handler) {
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).uploadImageBaidu(((MyApplication) MyApplication.getInstance()).getRequestFieldMap(), "stsToken", "upload").enqueue(new Callback<UploadImageBaidu>() {
            @Override
            public void onResponse(Call<UploadImageBaidu> call, Response<UploadImageBaidu> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getErrCode() == 0) {
                        String key = getFileNameNoEx(picFile);
                        UploadPicUtil.getInstance().uploadPicToBos(picFile, response.body().getAttachment().getAk(),
                                response.body().getAttachment().getSk(), response.body().getAttachment().getBucketName(),
                                response.body().getAttachment().getStsToken(),
                                response.body().getAttachment().getBucketName(),
                                key, new UploadPicUtil.OnFinishListener() {
                                    @Override
                                    public void onSuccess() {
                                        dismissLoadingDialog();
                                        try {
                                            JSONObject jsonObject = new JSONObject();
                                            jsonObject.put("imageId", key);
                                            handler.setProgressData(jsonObject);
                                            Logger.d("jsbridge_return", "imageId:" + key);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onFailure(String failReason) {
                                        dismissLoadingDialog();
                                        try {
                                            JSONObject jsonObject = new JSONObject();
                                            jsonObject.put("error", failReason);
                                            handler.setProgressData(jsonObject);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                    } else {
                        dismissLoadingDialog();
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("error", "error");
                            handler.setProgressData(jsonObject);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    dismissLoadingDialog();
                    try {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("error", "error");
                        handler.setProgressData(jsonObject);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<UploadImageBaidu> call, Throwable t) {
                dismissLoadingDialog();
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("error", "error");
                    handler.setProgressData(jsonObject);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /*
    * Java文件操作 获取不带扩展名的文件名
    */
    public String getFileNameNoEx(File nameFile) {
        String filename = nameFile.getName();
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }
}
